//
//  FANUserNetModel.swift
//  Weibo - Swift
//
//  Created by user on 16/4/19.
//  Copyright © 2016年 user. All rights reserved.
//

import UIKit

class FANUserNetModel: NSObject {
    
    
    static let sharedUserModel:FANUserNetModel = FANUserNetModel()
    
    var account: FANUserAccountModel?
    
    override init() {
        
        super.init()
        
        account = getUserModel()
        
    }
    
    var accessToken:String? {
        
        return account?.access_token
    }
    
    var isLogin:Bool {
        
        if accessToken == nil{
            
            print("accessToken为nil")
            
            return false
        }
        
        guard let date = account?.expiresDate else{
            
            return false
        }
        
        if NSDate().compare(date) == .OrderedAscending {
            
            return true
        }
        
        return false
    }
    
    
    func loadAccessToken(code:String, finished:(isSuccess:Bool)->()){
        
        /*
        必选	类型及范围	说明
        client_id	true	string	申请应用时分配的AppKey。
        client_secret	true	string	申请应用时分配的AppSecret。
        grant_type	true	string	请求的类型，填写authorization_code
        
        grant_type为authorization_code时
        必选	类型及范围	说明
        code	true	string	调用authorize获得的code值。
        redirect_uri	true	string	回调地址，需需与注册应用里的回调地址一致。
        */
        
        let urlString = "https://api.weibo.com/oauth2/access_token"
        
        let params = [
            
            "client_id" : WB_APP_KEY,
            "client_secret" : WB_APP_SECRET,
            "grant_type" : "authorization_code",
            "code" : code,
            "redirect_uri" : WB_REDIRECT_URI
        ]
        
        NetworkTools.sharedTools.request(FANRequestMethod.post, urlString: urlString, parameter: params, progress: nil) { (responseObject, error) -> () in
            
            if error != nil{
                print(error)
                finished(isSuccess: false)

                return
            }
            
            //            print(responseObject)
            
            guard let dict = responseObject as? [String:AnyObject] else{
                
                finished(isSuccess: false)

                return
            }
            
            let result = FANUserAccountModel(dict:dict)
            
            self.loadInfo(result,finished: finished)
        }
        
        
        
    }
    
    func  loadInfo(userModel:FANUserAccountModel,finished:(isSuccess:Bool)->()){
        
        let urlString = "https://api.weibo.com/2/users/show.json"
        
        let params = [
            
            "access_token":userModel.access_token ?? "",
            
            "uid":userModel.uid ?? ""
            
        ]
        
        NetworkTools.sharedTools.request(FANRequestMethod.get, urlString: urlString, parameter: params, progress: nil) { (responseObject, error) -> () in
            
            if error != nil{
                print(error)
                
                finished(isSuccess: false)
                
                return
            }
            
            guard let response = responseObject as? [String:AnyObject] else{
                
                finished(isSuccess: false)

                return
            }
            
            userModel.name = response["name"] as? String
            
            userModel.avatar_large = response["avatar_large"] as? String
            
            
            self.account = userModel
            
            finished(isSuccess: true)
            //            print(userModel.name)
            self.saveUserModel(userModel)
        }
        
        
        
    }
    
    private func saveUserModel(userModel:FANUserAccountModel){
        
        let path = (NSSearchPathForDirectoriesInDomains(.DocumentDirectory, .UserDomainMask, true).last! as NSString ) .stringByAppendingPathComponent("userModel.archive")
        
        NSKeyedArchiver.archiveRootObject(userModel, toFile: path)
    }
    
    private func getUserModel()->FANUserAccountModel?{
        
        let path = (NSSearchPathForDirectoriesInDomains(.DocumentDirectory, .UserDomainMask, true).last! as NSString ) .stringByAppendingPathComponent("userModel.archive")
        
        let result = NSKeyedUnarchiver.unarchiveObjectWithFile(path) as? FANUserAccountModel
        
        
        return result
    }
    

}
